package cn.buk.tms.flight.service;

import cn.buk.tms.entity.misc.EntDepartment;
import cn.buk.qms.service.BaseFlightOrderService;
import cn.buk.qms.service.FlightOrderService;
import cn.buk.tms.exception.BaseException;
import cn.buk.tms.flight.dto.FlightOfferPrice;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static cn.buk.common.JsonResult.STATUS_OK;
import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * CZ NDC自动开票
 * @author yfdai
 */
@Service
public class AutoTicketCzNdcWorker extends BaseFlightOrderService implements AutoTicketStrategy {

  private final FlightOrderService flightOrderService;

  @Autowired
  public AutoTicketCzNdcWorker(FlightOrderService flightOrderService) {
    this.flightOrderService = flightOrderService;
  }

  @Override
  public void autoTicketFlightOrder(int enterpriseId, String username, int orderId) {
    var flightOrder = flightOrderDao.getOrderDetailById(orderId);

    if (StringUtils.isBlank(flightOrder.getExternalOrderNo())) {
      //1.校验航班价格
      FlightOfferPrice fop = flightOrderService.checkFlightOrderPrice(enterpriseId, username, orderId);
      if (fop.getErrcode() > 0) {
        String remark = String.format("CZ_NDC_自动出票: %s (订单号：%s)", fop.getErrmsg(), flightOrder.getOrderNo());
        doSendAlert(enterpriseId, remark, null, EntDepartment.DEPT_TICKETING);
        return;
      }

      //确定价格，创建订单
      List<String> itemCodes = new ArrayList<>();
      for (var fareDto : fop.getSegments().get(0).getFareInfoDtos()) {
        //有更便宜的价格，发送信息提醒
        if (flightOrder.getPrice() > 0 && flightOrder.getPrice() > fareDto.getBaseAmount()) {
          //发出提醒
          var content = String.format("订单(%s, %s, %f)CZ_NDC询价时看到更低价格(%f, %s)", flightOrder.getOrderNo(),
                  flightOrder.getOperator(), flightOrder.getPrice(), fareDto.getBaseAmount(), fareDto.getFareBasisCode());
          sendFlightOrderAlertToWwAppChat(enterpriseId, content);
        }

        if (fareDto.getBaseAmount() == flightOrder.getParvalue() || fareDto.getBaseAmount() == flightOrder.getPrice()) {
          //航司的卖价等于票面价或者销售价，我司可能在航司的票面价的基础商加价出售 yfdai 2021-10-01
          //还有一种可能，就是没有匹配的价格：这样的情况一般是低价票，在之前预订编码时已经锁定了价格，现在再去查询价格就只有高价了，所以只能用BSP出票。
          itemCodes.add(fareDto.getOfferItemId());
          break;
        }
      }

      if (itemCodes.isEmpty()) {
        //未反馈匹配价格，停止用CZ NDC出票
        //标识该订单获取CZ NDC验价时出错，不再用NDC开票
        flightOrderDao.appendFlightOrderLog(enterpriseId, username, orderId, "CZ_NDC_未找到匹配价格");

        final String key = String.format(CZ_NDC_ORDER_KEY, enterpriseId, flightOrder.getOrderNo());
        final String value = JSON.toJSONString(fop.getErrmsg());

        redisDao.setAndExpire(key, value.getBytes(UTF_8), 60L * 10);

        return;
      }

      final String shoppingResponseId = fop.getShoppingResponseId();

      var jr = flightOrderService.confirmFlightOrderPrice(enterpriseId, username, orderId, shoppingResponseId, itemCodes);
      if (!STATUS_OK.equalsIgnoreCase(jr.getStatus())) {
        doSendAlert(enterpriseId, "CZ_NDC_自动出票: " + jr.getErrmsg(), "Dai", 0);

        final String key = String.format(CZ_NDC_ORDER_KEY, enterpriseId, flightOrder.getOrderNo());
        final String value = JSON.toJSONString(jr.getErrmsg());

        redisDao.setAndExpire(key, value.getBytes(UTF_8), 60L * 10);

        return;
      }

      //支付订单，等待完成
      jr = flightOrderService.payForFlightOrder(enterpriseId, username, orderId);
      if (!STATUS_OK.equalsIgnoreCase(jr.getStatus())) {
        doSendAlert(enterpriseId, "CZ_NDC_自动出票: " + jr.getErrmsg(), "Dai", 0);

        return;
      }
    }

    //同步订单状态，等待完成
    try {
      flightOrderService.syncFlightOrderStatus(enterpriseId, username, orderId, 1);
    } catch (BaseException e) {
      e.printStackTrace();
    }

  }
}
